import {Injectable} from '@angular/core';


@Injectable({
  providedIn: 'root'
})
export class CommonHttp {
  public http: XMLHttpRequest = null;

  constructor() {
    // @ts-ignore
    if (window.XMLHttpRequest) {
      this.http = new XMLHttpRequest();
    } else {
      // @ts-ignore
      this.http = new ActiveXObject('Microsoft.XMLHTTP');
    }
  }

  public get(url, headers?) {
    this.http.open('get', url, false);
    if (headers) {
      const that = this;
      const array = Object.getOwnPropertyNames(headers);
      array.forEach((key, index) => {
        that.http.setRequestHeader(key, headers[key]);
      });
    }
    this.http.send(null);
    if (this.http.status === 200) {
      return {
        isSuccess: true,
        data: this.http.responseText,
        http: this.http
      };
    } else {
      return {
        isSuccess: false,
        data: this.http.responseText,
        http: this.http
      };
    }
  }

  public post(url, data, headers?) {
    this.http.open('post', url, false);
    if (headers) {
      const that = this;
      const array = Object.getOwnPropertyNames(headers);
      array.forEach((key, index) => {
        that.http.setRequestHeader(key, headers[key]);
      });
    }
    let req = null;
    if (data) {
      req = JSON.stringify(data);
    }
    this.http.send(req);
    if (this.http.status === 200) {
      return {
        isSuccess: true,
        data: this.http.responseText,
        http: this.http
      };
    } else {
      return {
        isSuccess: false,
        data: this.http.responseText,
        http: this.http
      };
    }
  }

  public delete(url, headers?) {
    this.http.open('delete', url, false);
    if (headers) {
      const that = this;
      const array = Object.getOwnPropertyNames(headers);
      array.forEach((key, index) => {
        that.http.setRequestHeader(key, headers[key]);
      });
    }
    this.http.send(null);
    if (this.http.status === 200) {
      return {
        isSuccess: true,
        data: this.http.responseText,
        http: this.http
      };
    } else {
      return {
        isSuccess: false,
        data: this.http.responseText,
        http: this.http
      };
    }
  }

  public put(url, data, headers?) {
    this.http.open('put', url, false);
    if (headers) {
      const that = this;
      const array = Object.getOwnPropertyNames(headers);
      array.forEach((key, index) => {
        that.http.setRequestHeader(key, headers[key]);
      });
    }
    let req = null;
    if (data) {
      req = JSON.stringify(data);
    }
    this.http.send(req);
    if (this.http.status === 200) {
      return {
        isSuccess: true,
        data: this.http.responseText,
        http: this.http
      };
    } else {
      return {
        isSuccess: false,
        data: this.http.responseText,
        http: this.http
      };
    }
  }

}
